package jh.com.jhappbf.httputils;

import android.content.Context;
import android.graphics.Bitmap;
import androidx.collection.LruCache;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.Volley;

/**
 * @author Administrator
 */
public class VolleySingleton {
	private Context mContext;
	private RequestQueue mRequestQueue;
	private ImageLoader mImageLoader;
	private static VolleySingleton mVolleySingleton;

	private VolleySingleton(Context context) {
		mContext = context;
		mRequestQueue = getRequestQueue();
		long appMemorySize =Runtime.getRuntime().maxMemory()/1024;
		final int cacheSize = (int) (appMemorySize/8);
		mImageLoader = new ImageLoader(mRequestQueue, new ImageCache() {
			LruCache<String, Bitmap> imageCache = new LruCache<>(
					cacheSize);

			@Override
			public void putBitmap(String url, Bitmap bitmap) {
				imageCache.put(url, bitmap);
			}

			@Override
			public Bitmap getBitmap(String url) {
				return imageCache.get(url);
			}
		});
	}

	/**
	 * @summary 创建一个单例实例
	 * @context 应用程序的上下文
	 * @Return 返回 VolleySingleton 实例
	 */
	public synchronized static VolleySingleton getVolleyInstance(Context context) {
		if (mVolleySingleton == null) {
			mVolleySingleton = new VolleySingleton(context);
		}
		return mVolleySingleton;
	}

	/**
	 * @summary 获取请求队列
	 * @return 返回请求队列
	 */
	private RequestQueue getRequestQueue() {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(mContext);
		}
		return mRequestQueue;
	}

	/**
	 * @summary 添加请求
	 * @param request
	 */
	public <T> void addRequest(Request<T> request) {
//		request.setRetryPolicy(new DefaultRetryPolicy(2*1000,1,1.0f));
//		request.setShouldCache(false);
		mRequestQueue.add(request);
	}

	/**
	 * @summary 返回ImageLoader
	 * @return ImageLoader实例
	 */
	public ImageLoader getImageLoader() {
		return mImageLoader;
	}

}
